import { useCallback, useEffect, useRef, } from "react";

// useThrottle实现了节流: 将一定时间内的多次点击减少为一次点击
export const useThrottle = (func: (args: any) => void, duration: number, dep = []) => {
    const { current } = useRef({fun: func, valid: true});
    useEffect(() => {
        current.fun = func;
    }, [func, current]);
    return useCallback((args: void) => {
        if(!current.valid) return;
        current.valid = false;
        window.setTimeout(() => {
            current.fun(args);
            current.valid = true;
        }, duration);
    }, [current, duration])
}

